import React, { Component, Fragment } from 'react';
import { observable, action, computed, toJS } from 'mobx';
import { RouteLayout } from 'weaver-mobile-page';
import { Tools, Button, Modal, InputItem, Bubble } from "weaver-mobile";
import { cloneDeep } from "lodash";

import * as api from '../../apis/secretGuard';

const getLabel = Tools.getLabel;
const prompt = Modal.prompt;

class SecretGuardStore {
    @observable isSetted = false; //是否设置了密保问题
    @observable openRSA = "0"; //是否需要对密码进行加密
    @observable secStatus = false; //当前密保状态是否为启用
    @observable visible = false;
    @observable date = new Date();
    @observable current = 0;
    @observable layout = new RouteLayout.Store({ route: '/secretGuard' });
    @observable pslayout = new RouteLayout.Store({ route: '/passwordSetting' });
    @observable qa = [{ q: "", a: "" }];
    @observable checkStatus = [false];
    @observable answers = []; //存放密保问题验证的答案

    //描述
    @computed get desc() {
        if (!this.isSetted) {
            return (
                <Fragment>
                    <p>{`•${getLabel('386511',"什么是密保问题？")}`}</p>
                    <p>{getLabel('506872',"由用户设定的几个问题及对应答案组成，用于找回E-cology登录密码。")}</p>
                    <p>{`•${getLabel('386512',"如何用密保问题找回密码？")}`}</p>
                    <p>{getLabel('386513',"您可以通过登录页面中的“忘记密码”选择“密保问题”验证答案，找回密码。")}</p>
                </Fragment>
            )
        } else {
            return (
                <Fragment>
                    <p>{`•${getLabel('386509',"密保问题忘了怎么办？")}`}</p>
                    <p>{getLabel('386510',"可采用发送短信或发送邮件方式找回密码,若这两种方式都未开启，则联系系统管理员解决。")}</p>
                </Fragment>
            )
        }
    }

    //外部的按钮
    @computed get outterBtns() {
        if (!this.isSetted) {
            return (
                <Button type="primary" onClick={this.setSec}>{getLabel('386514',"立即设置")}</Button>
            )
        } else {
            if (this.secStatus) {
                return (
                    <Fragment>
                        <Button type="primary" onClick={this.stop}>{getLabel('26471',"停用")}</Button>
                        <Button type="primary" onClick={this.modify}>{getLabel('103',"修改")}</Button>
                    </Fragment>
                )
            } else {
                return (
                    <Button type="primary" onClick={this.startUse}>{getLabel('26472',"启用")}</Button>
                )
            }
        }
    }

    @computed get stepBtns() {
        return [
            <Button type="primary" onClick={this.nextStep}>{getLabel(1402, '下一步')}</Button>,
            [
                <Button onClick={this.prevStep}>{getLabel(1876, '上一步')}</Button>,
                <Button type="primary" onClick={this.nextStep}>{getLabel(1402, '下一步')}</Button>,
            ],
            <Button type="primary" onClick={this.finish}>{getLabel(555, '完成')}</Button>,
        ][this.current];
    }

    @computed get stepTitle() {
        const titles = [getLabel('386521', "填写密保问题"), getLabel('386522', "验证密保问题"), getLabel('386523', "完成密保问题")];
        return titles[this.current]
    }

    @computed get iconColor() {
        const colors = ["#55b1f9", "#999", "#999"];

        if (this.isChecked()) {
            [1, 2].forEach(val => colors[val] = "#55b1f9");
        }

        return colors;
    }

    //是否选中了全部
    @computed get isCheckAll() {
        return this.checkStatus.every(b => b);
    }

    //选中状态check框的索引值
    @computed get checkedIndex() {
        return this.checkStatus.map((v, i) => v && i).filter(v => typeof v == "number");
    }

    /**
     * 概述：是否设置了密保问题
     */
    @action isSettedQuestion = () => {
        api.isSettedQuestion().then(res => {
            if (res.status == 1) {
                Object.keys(res).forEach(key => this[key] = res[key]);
            }
        })
    }

    /**
     * 概述：获取密保问题和答案
     */
    @action getPasswordQuestion = () => {
        api.getPasswordQuestion().then(res => {
            const { tableinfo: { datas } } = res;

            if (datas.length) {
                this.qa = datas.map(data => { return { q: data.question, a: data.answer } });
                this.checkStatus = datas.map(() => false);
            } 
        })
    }

    /**
     * 概述：保存密保问题和答案
     */
    @action insertQuestion = (cb) => {
        const params = {};

        this.qa.forEach((data, index) => {
            params[`question_${index}`] = data.q;
            params[`answer_${index}`] = data.a;
        });

        api.insertQuestion(params).then(res => {
            if (res.result == "true") {
                cb && cb();
            } else {
                Bubble.error(res.message);
            }
        })
    }

    /**
     * 概述：切换密保状态
     */
    @action changePswSwitch = (params, cb) => {
        api.changePswSwitch(params).then(res => {
            if (res.result == "true") {
                cb && cb();
            } else {
                Bubble.warning(res.message);
                this.date = new Date();
            }
        })
    }

    /**
     * 概述：密码校验
     * @param  {Function} cb [回调函数]
     */
    @action verifyPswd = (params, cb) => {
        api.verifyPswd(params).then(res => {
            const { result, message } = res;

            if (result == "true") {

                cb && cb();
            } else {
                Bubble.warning(message);
                this.date = new Date();
            }
        })
    }

    /**
     * 概述：立即设置
     */
    @action setSec = () => {
        this.clickType = "setSec";
        this.visible = true;
    }

    /**
     * 概述：关闭modal框
     */
    @action handleModalClose = () => {
        this.visible = false;
    }

    /**
     * 概述：停用
     */
    stop = () => {
        this.clickType = "stop";
        this.visible = true;
    }

    /**
     * 概述：修改
     */
    modify = () => {
        this.clickType = "modify";
        this.visible = true;
    }

    /**
     * 概述：启用
     */
    startUse = () => {
        this.clickType = "startUse";
        this.visible = true;
    }

    /**
     * 概述：下一步
     */
    nextStep = () => {
        if (this.current == 0) {
            const qa = this.qa;
            if (qa.length == 0) {
                Bubble.warning(getLabel('386515', "请填写密保问题！"));
                return;
            }
            if (!this.isSecQaComplete()) {
                Bubble.warning(getLabel('386497', "必填信息不完整！"))
                return;
            }
            //初始化answers
            this.answers = [];
            qa.forEach(() => this.answers.push(""));
            this.current++;
            return;
        }
        if (this.current == 1) {
            if (!this.isAnswerComplete()) return;
            if (!this.isAnswerMatch()) return;
            this.insertQuestion(() => { this.current++ });
        }


    }

    /**
     * 概述：上一步
     */
    prevStep = () => {
        this.current--;
    }

    /**
     * 概述：完成
     */
    finish = () => {
        const pswd = this.verifyFormParams.pswd;
        this.changePswSwitch({ pswd, checked: true,preserve:true }, () => {
            this.history.go(-1);
            this.current = 0;
            this.isSetted = true;
            this.secStatus = true;
        })
    }

    /**
     * 概述：验证密保问题阶段，密保答案是否填写完整
     */
    isAnswerComplete = () => {
        if (this.answers.some(ans => !ans)) {
            Bubble.warning(getLabel('386497', "必填信息不完整！"))
            return false;
        }
        return true
    }

    /**
     * 概述：验证密保问题阶段,密保答案是否和之前填写的一致
     */
    isAnswerMatch = () => {
        for (let i = 0; i < this.qa.length; i++) {
            const a = this.qa[i].a;
            if (this.answers[i] != a) {
                Bubble.warning(`${getLabel(522178,"问题{param}输入的答案与问题不匹配，请重新输入！").replace("{param}", i+1)}`);
                return false
            }
        }
        return true;
    }

    /**
     * 概述：校验密保问题是否完整
     */
    isSecQaComplete = () => {
        return this.qa.every(data => data.q && data.a);
    }

    /**
     * 概述：验证
     */
    verify = (cb) => {
        const formParams = this.verifyFormParams;

        if (!formParams) {
            Bubble.warning(getLabel('386497', "必填信息不完整！"));
            return
        }
        if (!formParams.pswd || !formParams.validatecode) {
            Bubble.warning(getLabel('386497', "必填信息不完整！"));
            return
        }

        const ct = this.clickType;

        if (["setSec", "modify"].includes(ct)) {
            this.verifyPswd(formParams, () => {
                this.current = 0;
                this.qa = [{ q: "", a: "" }];
                this.checkStatus = [false];
                
                //获取设置的密保问题
                this.getPasswordQuestion();
                //跳转到密保设置页面
                this.history.push(this.inTab ? this.pslayout.path : this.layout.path);
                //关闭弹框
                this.handleModalClose();
            })
        }
        if (["startUse", "stop"].includes(ct)) {
            const b = (ct == 'startUse') ? true : false
            this.changePswSwitch({ ...formParams, checked: b }, () => {
                this.secStatus = b;
                this.handleModalClose();
            });
        }

    }

    handleIconBtnClick = (index) => {
        if (index == 0) {
            this.addQa();
        } else if (index == 1) {
            this.copyQa();
        } else {
            this.delQa()
        }
    }

    addQa = () => {
        this.qa.push({ q: "", a: "" });
        this.checkStatus.push(false);
    }

    copyQa = () => {
        const qa = this.qa;
        const items = this.checkedIndex.map(index => qa[index]);
        this.qa = [...qa, ...cloneDeep(items)];
        this.checkedIndex.forEach(() => this.checkStatus.push(false))
    }

    delQa = () => {
        const ci = this.checkedIndex,
            qa = this.qa,
            cs = this.checkStatus;

        this.qa = qa.filter((o, i) => !ci.includes(i));
        this.checkStatus = cs.filter((o, i) => !ci.includes(i));

        this.cancelCheck();
    }

    /**
     * 概述：是否选中了某个check框
     */
    isChecked = () => {
        return this.checkStatus.some(b => b);
    }

    /**
     * 概述：全选
     */
    checkAll = () => {
        if (this.isCheckAll) {
            this.checkStatus = this.checkStatus.map(b => !b);
        } else {
            this.checkStatus.forEach((b, i) => {
                if (!b) {
                    this.checkStatus[i] = true;
                }
            })
        }
    }

    /**
     * 概述：取消选中
     */
    cancelCheck = () => {
        this.checkStatus.forEach((v, i) => {
            if (v) {
                this.checkStatus[i] = false;
            }
        })
    }


    /**
     * 概述：check框事件回调
     * @param  {[Number]} index [check框的索引值]
     */
    handleCk = (index) => {
        this.checkStatus[index] = !this.checkStatus[index];
    }

    /**
     * 概述：填写密保问题
     * @param  {[String]} v     [表单元素的值]
     * @param  {[Number]} index [索引值]
     * @param  {[String]} type  [标识问题还是答案]
     */
    handleQaChange = (v, index, type) => {
        this.qa[index][type] = v;
    }


    /**
     * 概述：验证密保问题（填写答案）
     * @param  {[String]} v [答案]
     * @param  {[Number]} index [索引值]
     */
    handleAnswerChange = (v, index) => {
        this.answers[index] = v;
    }


    setFormParams = (formParams) => {
        this.verifyFormParams = formParams;
    }

    setHistory = (history) => {
        this.history = history;
    }

    setPageStatus = (inTab) => {
        this.inTab = inTab;
    }

    onWrapTouchStart = (e) => {
        // fix touch to scroll background page on iOS
        if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
            return;
        }
        const pNode = this.closest(e.target, '.am-modal-content');
        if (!pNode) {
            e.preventDefault();
        }
    }

    closest = (el, selector) => {
        const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
        while (el) {
            if (matchesSelector.call(el, selector)) {
                return el;
            }
            el = el.parentElement;
        }
        return null;
    }
}

export const secretGuardStore = new SecretGuardStore();